import React, { useEffect, useState } from "react";

import {
  Button,
  ColorPicker,
  Form,
  Input,
  Select,
  Switch,
  Table,
  UploadFile,
} from "antd";
import { debounce } from "../../../utils/utils";
import NoneSvg from "../../../assets/none.svg";
import { DeleteOutlined } from "@ant-design/icons";
import ImageUpload from "../Material/Image/ImageUpload";
import { useCurrentComponent } from "../../../hooks/useCurrentComponent";

const COMPACT_STYLE = {
  panel: "border rounded-md transition-all duration-200",
  title: "px-2 py-1.5 text-sm",
  content: "px-2 py-1.5 space-y-1.5",
  input: "text-xs py-1 leading-4",
  select: "text-xs",
  icon: "text-xs p-1",
};

const Attrbuites: React.FC = () => {
  const { componentConfig, currentElement, setCurComponentProps, curComponet } = useCurrentComponent()
  const [form] = Form.useForm();
  const [expandedPanels, setExpandedPanels] = useState<Record<string, boolean>>({});



  useEffect(() => {
    if (!currentElement) return;
    let props = {};
    if (Object.keys(currentElement.props).length > 0) {
      props = currentElement.props;
    } else {
      props = componentConfig[currentElement.name].defaultProps;
    }
    form.setFieldsValue(props);
  }, [currentElement]);

  const togglePanel = (key: string) => {
    setExpandedPanels((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  if (!currentElement)
    return (
      <div className="flex flex-col gap-3 items-center text-gray-500 ">
        <img src={NoneSvg} />
        <p>请选择组件</p>
      </div>
    );

  const handleChange = debounce((value: any) => {
    if (value.upload) {
      delete value.upload;
    }
    setCurComponentProps({ ...curComponet?.props, ...value });
  });

  return (
    <div>
      <Form
        form={form}
        initialValues={componentConfig[currentElement.name].defaultProps}
        onValuesChange={(_, value) => handleChange(value)}
      >
        {componentConfig[currentElement.name].attrs &&
          Object.entries(componentConfig[currentElement.name].attrs!).map(
            ([key, value]) => {
              const isExpanded = expandedPanels[key] ?? true;
              if (value.type === "tableColumn") {
                return (
                  <Form.List key={key} name={key}>
                    {(fields, { add, remove }) => {
                      const columns = [
                        {
                          title: "标题",
                          dataIndex: "title",
                          render: (_: any, record: any) => (
                            <Form.Item
                              name={[record.name, "title"]}
                              key={record.name}
                              rules={[{ required: true, message: "请输入标题" }]}
                            >
                              <Input
                                placeholder="请输入标题"
                                className="text-xs h-6"
                              />
                            </Form.Item>
                          ),
                        },
                        {
                          title: "Key",
                          dataIndex: "key",
                          render: (_: any, record: any) => (
                            <Form.Item
                              name={[record.name, "key"]}
                              key={record.name}
                              rules={[{ required: true, message: "请输入Key" }]}
                            >
                              <Input
                                placeholder="请输入Key"
                                className="text-xs h-6"
                              />
                            </Form.Item>
                          ),
                        },
                        {
                          title: "操作",
                          dataIndex: "operation",
                          render: (_: any, record: any) => (
                            <Button
                              type="text"
                              icon={<DeleteOutlined />}
                              onClick={() => remove(record.name)}
                              className="text-gray-500 hover:text-red-500 p-0"
                            />
                          ),
                        },
                      ];

                      return (
                        <div key={key}>
                          <div
                            className={`${COMPACT_STYLE.title
                              } flex items-center justify-between cursor-pointer ${value.type === "tableColumn" ? "bg-gray-100" : "bg-gray-50"
                              } hover:bg-gray-200 rounded-t-md`}
                            onClick={() => togglePanel(key)}
                          >
                            <div className="flex items-center gap-1.5">
                              {value.type === "tableColumn" && (
                                <span className="w-1.5 h-1.5 bg-blue-400 rounded-full" />
                              )}
                              <span className="text-gray-700 font-medium">
                                表格列
                              </span>
                            </div>
                            <span
                              className={`text-gray-500 text-xs transform transition-transform ${!isExpanded && "rotate-180"
                                }`}
                            >
                              ▲
                            </span>
                          </div>
                          <div
                            className={`${COMPACT_STYLE.content
                              } bg-white rounded-b-md ${isExpanded ? "block" : "hidden"}`}
                          >
                            <Table
                              columns={columns}
                              dataSource={fields}
                              pagination={false}
                              rowKey={(record) => record.key}
                              className="ant-table-compact"
                              style={{ fontSize: "12px" }}
                            />
                            <Button
                              type="dashed"
                              onClick={() => add()}
                              block
                              style={{ marginTop: "10px", fontSize: "12px", height: "24px", lineHeight: "24px" }}
                            >
                              + 新增一列
                            </Button>
                          </div>
                        </div>
                      );
                    }}
                  </Form.List>
                );
              }
              else if (value.type === "selectOptions") {
                return (
                  <Form.List key={key} name={key}>
                    {(fields, { add, remove }) => {
                      const columns = [
                        {
                          title: "显示文本",
                          dataIndex: "label",
                          render: (_: any, record: any) => (
                            <Form.Item
                              name={[record.name, "label"]}
                              rules={[{ required: true, message: "请输入显示文本" }]}
                              className="!mb-0"
                            >
                              <Input placeholder="显示文本" className="text-xs h-6" />
                            </Form.Item>
                          ),
                        },
                        {
                          title: "值",
                          dataIndex: "value",
                          render: (_: any, record: any) => (
                            <Form.Item
                              name={[record.name, "value"]}
                              rules={[{ required: true, message: "请输入值" }]}
                              className="!mb-0"
                            >
                              <Input placeholder="值" className="text-xs h-6" />
                            </Form.Item>
                          ),
                        },
                        {
                          title: "操作",
                          dataIndex: "operation",
                          render: (_: any, record: any) => (
                            <Button
                              type="text"
                              icon={<DeleteOutlined className="!text-xs" />}
                              onClick={() => remove(record.name)}
                              className="!text-gray-500 hover:!text-red-500 !p-0"
                            />
                          ),
                        },
                      ];

                      return (
                        <div className={COMPACT_STYLE.panel}>
                          <div
                            className={`${COMPACT_STYLE.title} flex items-center justify-between cursor-pointer bg-gray-100 hover:bg-gray-200 rounded-t-md`}
                            onClick={() => togglePanel(key)}
                          >
                            <div className="flex items-center gap-1.5">
                              <span className="w-1.5 h-1.5 bg-green-400 rounded-full" />
                              <span className="text-gray-700 font-medium">{value.label}</span>
                            </div>
                            <span
                              className={`text-gray-500 text-xs transform transition-transform ${!expandedPanels[key] && "rotate-180"
                                }`}
                            >
                              ▲
                            </span>
                          </div>

                          <div
                            className={`${COMPACT_STYLE.content} bg-white rounded-b-md ${expandedPanels[key] ? "block" : "hidden"
                              }`}
                          >
                            <Table
                              columns={columns}
                              dataSource={fields}
                              pagination={false}
                              rowKey={(record) => record.key}
                              className="ant-table-compact"
                              bordered
                              size="small"
                            />
                            <Button
                              type="dashed"
                              onClick={() => add({ label: "新选项", value: "new_value" })}
                              block
                              className="!text-xs !h-6 !leading-4 mt-2"
                            >
                              + 新增选项
                            </Button>
                          </div>
                        </div>
                      );
                    }}
                  </Form.List>
                );
              }
              else {
                return (
                  <Form.Item
                    key={key}
                    name={key}
                    label={false}
                    className="!mb-2"
                  >
                    <div className={COMPACT_STYLE.panel}>
                      {/* 标题区域 */}
                      <div
                        className={`${COMPACT_STYLE.title
                          } flex items-center justify-between cursor-pointer 
                                            ${value.type === "tableColumn"
                            ? "bg-gray-100"
                            : "bg-gray-50"
                          } 
                                            hover:bg-gray-200 rounded-t-md`}
                        onClick={() => togglePanel(key)}
                      >
                        <div className="flex items-center gap-1.5">
                          {value.type === "tableColumn" && (
                            <span className="w-1.5 h-1.5 bg-blue-400 rounded-full" />
                          )}
                          <span className="text-gray-700 font-medium">
                            {value.label}
                          </span>
                        </div>
                        <span
                          className={`text-gray-500 text-xs transform transition-transform ${!isExpanded && "rotate-180"
                            }`}
                        >
                          ▲
                        </span>
                      </div>

                      {/* 内容区域 */}
                      {isExpanded && (
                        <div
                          className={`${COMPACT_STYLE.content} bg-white rounded-b-md`}
                        >
                          {(() => {
                            switch (value.type) {
                              case "input":
                                return (
                                  <Form.Item name={key}>
                                    <Input
                                      className={`${COMPACT_STYLE.input} border-gray-200`}
                                    />
                                  </Form.Item>
                                );

                              case "select":
                                return (
                                  <Form.Item name={key}>
                                    <Select
                                      className={`w-full ${COMPACT_STYLE.select}`}
                                      options={value.options}
                                    />
                                  </Form.Item>
                                );

                              case "switch":
                                return (
                                  <Form.Item name={key} valuePropName="checked">
                                    <Switch className="!ml-1" size="small" />
                                  </Form.Item>
                                );

                              case "colorSelect":
                                return (
                                  <Form.Item name={key}>
                                    <ColorPicker
                                      size="small"
                                      panelRender={(
                                        _,
                                        { components: { Presets } }
                                      ) => (
                                        <div className="custom-picker rounded-md shadow-sm p-1.5">
                                          <Presets />
                                        </div>
                                      )}
                                    />
                                  </Form.Item>
                                );
                              case "upload":
                                return (
                                  <Form.Item name={key}>
                                    <div className="flex items-center gap-1.5">
                                      <ImageUpload
                                        id={1}
                                        disabled={false}
                                        maxSize={5}
                                        allowedTypes={['image/jpeg', 'image/png', 'image/webp']}
                                      />
                                    </div>
                                  </Form.Item>)
                            }
                          })()}
                        </div>
                      )}
                    </div>
                  </Form.Item>
                );
              }
            }
          )}
      </Form>
    </div>
  );
};

export default Attrbuites;